package com.lmk.exception;


import com.lmk.enums.GlobalErrorCode;
import com.lmk.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
// 日志器注解
@Slf4j
public class MyGlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public JSONResult CustomException(Exception e){
        return JSONResult.error(GlobalErrorCode.ERROE);
    }

    @ExceptionHandler(MyGlobalCustomException.class)
    public JSONResult CustomException(MyGlobalCustomException e){
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult CustomException(MethodArgumentNotValidException e){
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuffer sbf = new StringBuffer();
        sbf.append("出错了！原因是：");
        // 2.2.遍历得到所有异常提示语
        allErrors.forEach(objectError ->
                sbf.append(objectError.getDefaultMessage()).append("--"));
        return JSONResult.error(sbf.toString(),"100");
    }
}
